package com.mallcai.bigdata.ladon.service.report.impl.handler.support;

import org.springframework.jdbc.core.PreparedStatementSetter;

import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Date;
import java.util.Map;

/**
 * @author feixy
 * @version 1.0
 * @date 2019-07-20 09:49
 */
public class OldMapParamPreparedStatementSetter implements PreparedStatementSetter {

    private final Map<Integer, Object> params; // 查询参数
    private final Integer timeout; // 查询超时时间

    public OldMapParamPreparedStatementSetter(Map<Integer, Object> params, Integer timeout) {
        this.params = params;
        this.timeout = timeout;
    }

    @Override
    public void setValues(PreparedStatement ps) throws SQLException {
        if (timeout != null && timeout > 0 ){
            ps.setQueryTimeout(timeout);
        }
        //写入预编译时的参数
        if (params != null && params.size() > 0) {
            Object obj;
            String objStr;
            for (Map.Entry<Integer, Object> entry : params.entrySet()) {
                obj = entry.getValue();
                Integer key = entry.getKey();
                objStr = String.valueOf(obj);
                if (obj instanceof String) { //字符串
                    ps.setString(key, objStr);
                } else if (obj instanceof Integer) { //整数类型
                    ps.setInt(key, Integer.parseInt(objStr));
                } else if (obj instanceof Long) {
                    ps.setLong(key, Long.valueOf(objStr));
                } else if (obj instanceof Boolean) { //布尔类型
                    ps.setBoolean(key, Boolean.valueOf(objStr));
                } else if (obj instanceof Double) {
                    ps.setDouble(key, Double.valueOf(objStr));
                } else if (obj instanceof Float) {
                    ps.setFloat(key, Float.valueOf(objStr));
                } else if (obj instanceof Date) {
                    Date utilDate = (Date)obj;
                    ps.setDate(key,new java.sql.Date(utilDate.getTime()));
                }
                else {
                    ps.setObject(key, obj);
                }
            }
        }
    }
}
